package com.ftp.longdistance.annotation;

import com.ftp.longdistance.util.ClassUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author tanyongpeng
 * <p>
 *     反射创建对象
 * </p>
 */
@Component
@Slf4j
public class GetConnectionType<T> {

    public T getConnectionType(String ftpType,String packageName){
        log.info("登录环境 = {}",ftpType);
        T t = null;
        try {
            Set<Class<?>> classes = ClassUtils.getClasses(packageName);
            for(Class c:classes){
                if(c.isAnnotationPresent(FileType.class)){
                    if (fileType(c).value().equals(ftpType)){
                       t = (T) Class.forName(c.getName()).getDeclaredConstructor().newInstance();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    public  T getConnectionFileType(String ftpType,String packageName){
        T t = null;
        try {
            Set<Class<?>> classes = ClassUtils.getClasses(packageName);
            for(Class c:classes){
                if(c.isAnnotationPresent(FileType.class)){
                    if (fileType(c).value().equals(ftpType)){
                        Object[] enumConstants = c.getEnumConstants();
                        t = (T) enumConstants[0];
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }


    public static FileType fileType(Class c){
       return (FileType) c.getAnnotation(FileType.class);
    }


}
